package com.ruoyi.common.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.util.List;

public class FreeImagesToPdf {

    final static String outputPath = "/opt/xinyidai/shouquanshunew/";

    public static String generatePdfByImg(List<String> images) {
        // 生成唯一文件名，避免冲突
        String fileName = "pdf_" + System.currentTimeMillis() + ".pdf";

        try (PDDocument document = new PDDocument()) {

            for (String imageUrl : images) {
                String newUrl = imageUrl.replace("https://credit.hd.gov.cn:8081/api/profile", "/xinyidai/uploadPath");
                File file = new File(newUrl);
                BufferedImage awtImage = ImageIO.read(file);
                PDPage page = new PDPage(PDRectangle.A4);
                document.addPage(page);

                PDImageXObject pdImage = PDImageXObject.createFromByteArray(document, toByteArray(awtImage, getImageFormat(newUrl)), null);

                try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                    float scale = calculateScale(awtImage, PDRectangle.A4);
                    float scaledWidth = awtImage.getWidth() * scale;
                    float scaledHeight = awtImage.getHeight() * scale;
                    float offsetX = (PDRectangle.A4.getWidth() - scaledWidth) / 2;
                    float offsetY = (PDRectangle.A4.getHeight() - scaledHeight) / 2;

                    contentStream.drawImage(pdImage, offsetX, offsetY, scaledWidth, scaledHeight);
                }
            }

            document.save(outputPath + fileName);
            return outputPath + fileName; // 返回文件路径

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 工具方法：将BufferedImage转为字节数组
    private static byte[] toByteArray(BufferedImage image, String format) throws Exception {
        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
        ImageIO.write(image, format, baos);
        return baos.toByteArray();
    }

    // 工具方法：从URL推断图片格式（用于ImageIO.write）
    private static String getImageFormat(String url) {
        String lowerUrl = url.toLowerCase();
        if (lowerUrl.endsWith(".png")) return "png";
        else if (lowerUrl.endsWith(".jpg") || lowerUrl.endsWith(".jpeg")) return "jpg";
        else if (lowerUrl.endsWith(".gif")) return "gif";
        else return "png"; // 默认
    }

    // 工具方法：计算图片缩放比例，适应A4页面
    private static float calculateScale(BufferedImage image, PDRectangle page) {
        float scaleX = page.getWidth() / image.getWidth();
        float scaleY = page.getHeight() / image.getHeight();
        return Math.min(scaleX, scaleY) * 0.9f; // 留10%边距
    }
}